package DAL.JDBC;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import DAL.Entites.GameImage;

public class GameImageJDBC {
	Connection conn;

	String tableName = "gameimages"; 

	public GameImageJDBC(Connection connection) {
		this.conn = connection;
	}
	
	public void insert(int GameId, String ImagePath) {
		// this is for selecting db incase we do insert first
		// ((DriverManagerDataSource)dataSource).setUrl("jdbc:mysql://localhost:3306/TestData");
		String SQL = String.format("insert into %s values(%s,'%s')", tableName, GameId, ImagePath);
		
		try {
			Statement st = this.conn.createStatement();
			st.execute(SQL);
			st.close();
			System.out.println("Created Record");
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}
		return;
	}
	
	private GameImage mapRow(ResultSet rs) throws SQLException {
		GameImage image = new GameImage(
				rs.getInt("GameID"), 
				rs.getString("Image"));
		System.out.println("mapRow");

		return image;
	}
	
	public List<GameImage> listImagesByGameId(int GameId) {
		List<GameImage> images = new ArrayList<GameImage>();
		String SQL = String.format("select * from %s where GameID = %s ", tableName, GameId);
		try {
			Statement st = conn.createStatement();
			for (ResultSet rs = st.executeQuery(SQL); rs.next();) {
				images.add(mapRow(rs));
			}
			st.close();
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}

		return images;
	}
}
